<template>
  <div class="card-list-container">
    <el-scrollbar ref="scrollbarRef" style="width: calc(100vw - 250px)" @wheel="handleScroll">
      <div class="card-list">
        <el-card
          v-for="(item, index) in cardData"
          :key="item.id || index"
          class="card-item"
          shadow="hover"
          @contextmenu.prevent="onContextmenu($event, item)"
        >
          <template v-if="item.title" #header>
            <div class="card-header flex justify-between items-center">
              <span>{{ item.title }}</span>
              <el-tooltip
                :show-after="500"
                :content="item.connected ? '已连接' : '未连接'"
                placement="bottom"
                effect="light"
              >
                <el-icon :class="item.connected ? 'text-green-500' : 'text-red-500'" class="ml-2">
                  <Connection />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-content">
            <el-text
              v-if="!item.props || item.props.length === 0"
              class="flex justify-center w-full"
            >
              暂无数据
            </el-text>
            <el-descriptions :column="1" border>
              <el-descriptions-item v-for="p in item.props" :key="p.propName">
                <template #label>
                  {{ p.propName }}
                </template>
                <el-text truncated style="max-width: 200px">{{ p.propValue }}</el-text>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
        <AgelContextMenu
          v-model="contextMenu.show"
          :x="contextMenu.x"
          :y="contextMenu.y"
          :menus="contextMenu.data"
          @select="contextMenu.onSelect"
        />
      </div>
    </el-scrollbar>

    <!-- 配置详情弹窗 -->
    <el-dialog
      v-if="dialogDetailVisible"
      v-model="dialogDetailVisible"
      width="700"
      title="设备修改"
    >
      <DeviceDetail :form-data="dialogDetailData" @close="handleCloseDialog" />
    </el-dialog>
    <!-- 配置详情弹窗 End -->
  </div>
</template>

<script setup lang="ts">
import { useDevicesStore } from "@/store/business/devices.store";
import { Connection } from "@element-plus/icons-vue";
import DeviceAPI from "@/api/business/device.api";
import deviceApi from "@/api/business/device.api";
import DeviceDetail from "@/views/business/devices/components/DeviceDetail.vue";
import { SignalrToken } from "@/enums/business/signalrToken.enum";
import { useSignalRStore } from "@/store/modules/signalr.store";

const devicesStore = useDevicesStore();
const cardData = devicesStore.activeDeviceCardList;

const scrollbarRef = ref();
const handleScroll = (event: WheelEvent) => {
  closeContextMenu();

  const scrollWrapper = scrollbarRef.value?.wrapRef;
  if (!scrollWrapper) return;

  const hasHorizontalScroll = scrollWrapper.scrollWidth > scrollWrapper.clientWidth;
  if (!hasHorizontalScroll) return;

  const deltaY = event.deltaY || -(event as any).wheelDelta || 0;
  const newScrollLeft = scrollWrapper.scrollLeft + deltaY;

  scrollbarRef.value.setScrollLeft(newScrollLeft);
};

// region signalr

const signalrStore = useSignalRStore();
onMounted(() => {
  signalrStore.subscribe(
    SignalrToken.DeviceConnectStatus,
    (deviceId: number, isConnected: boolean) => {
      const item = cardData.find((item: any) => item.id === deviceId);
      item.connected = isConnected;
    }
  );
  signalrStore.subscribe(SignalrToken.DeviceVals, (deviceId: number, deviceVals: any) => {
    // console.log("deviceVals", deviceId, deviceVals);
    const item = cardData.find((item: any) => item.id === deviceId);
    item.props.length = 0;
    Object.keys(deviceVals).forEach((key) => {
      item.props.push({
        propName: key,
        propValue: deviceVals[key],
      });
    });
  });
});

// endregion

// region 右键菜单

const MENU_NAME = {
  Config: "设备配置",
  Connect: "连接",
  Disconnect: "断开",
};

const contextMenuDevice = ref<CardItem | null>(null);
const contextMenu = reactive({
  device: {},
  show: false,
  x: 0,
  y: 0,
  data: [],
  onSelect: (item: any) => {
    console.log(item);
    if (contextMenuDevice.value) {
      // 根据当前设备状态执行不同操作
      if (item.title === MENU_NAME.Connect) {
        // 执行连接操作
        DeviceAPI.connect(contextMenuDevice.value.id).then(() => {
          ElMessage.success(`${contextMenuDevice.value.title}连接成功`);
        });
      } else if (item.title === MENU_NAME.Disconnect) {
        // 执行断开操作
        DeviceAPI.disconnect(contextMenuDevice.value.id).then(() => {
          ElMessage.success(`${contextMenuDevice.value.title}已断开连接`);
        });
      } else if (item.title === MENU_NAME.Config) {
        // 打开设置页
        handleOpenDialog(contextMenuDevice.value.id);
      }
    }
  },
});

function onContextmenu(e: MouseEvent, device: CardItem) {
  contextMenuDevice.value = device; // 保存当前设备

  // 根据设备连接状态动态生成菜单项
  contextMenu.data = [
    { title: MENU_NAME.Config, icon: "Setting" },
    { title: device.connected ? MENU_NAME.Disconnect : MENU_NAME.Connect, icon: "Connection" },
  ];

  contextMenu.show = true;
  contextMenu.x = e.clientX;
  contextMenu.y = e.clientY;
  e.preventDefault();
}
const closeContextMenu = () => {
  contextMenu.show = false;
};

// endregion

// region 设备参数弹窗

const dialogDetailVisible = ref(false);
const dialogDetailData = ref<DeviceConfig>();

function handleOpenDialog(id: number) {
  deviceApi.getDeviceConfig(id).then((res) => {
    dialogDetailData.value = res;
    dialogDetailVisible.value = true;
  });
}
function handleCloseDialog() {
  dialogDetailVisible.value = false;
}

// endregion
</script>

<style scoped>
:deep(.el-card__header) {
  padding: 10px;
}
:deep(.el-card__body) {
  padding: 10px;
}
.card-list-container {
  width: 100%;
}

.card-list {
  padding: 8px;
  display: flex;
  width: fit-content;
  gap: 10px;
}

.card-item {
  margin-bottom: 0px;
  flex-shrink: 0;
}

.card-item:last-child {
  margin-bottom: 0;
}

.card-header {
  font-weight: 600;
}

.card-content {
  line-height: 1.6;
}
</style>
